package org.remas.service;

import static org.apache.commons.lang.StringUtils.isBlank;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNRevision;

import java.io.File;

public class RemasSvn implements IRemasSvn{
	private SVNClientManager svnClientManager;
	private static Log logger = LogFactory.getLog(RemasSvn.class);

	public void setSvnClientManager(SVNClientManager svnClientManager) {
		this.svnClientManager = svnClientManager;
	}

	public void checkOut(String svnUrl, File workingDir) throws SVNException {
		logger.info(new StringBuilder("co ").append(svnUrl).append(" ").append(workingDir==null?null:workingDir.getAbsolutePath()));
		if(workingDir == null || isBlank(svnUrl)) {
			return;
		}
		SVNURL svnURL = SVNURL.parseURIDecoded(svnUrl);
		long revision = svnClientManager.getUpdateClient().doCheckout(svnURL, workingDir, SVNRevision.create(0), SVNRevision.HEAD, SVNDepth.INFINITY, false);
		logger.info("co success, revision "+revision);
	}

	/**
	 * Initializing FSRepositoryFactory, SVNRepositoryFactoryImpl and DAVRepositoryFactory
	 */
	public void init() {
		FSRepositoryFactory.setup();
		DAVRepositoryFactory.setup();
		SVNRepositoryFactoryImpl.setup();
	}
}
